package com.roadjava.demo09.handler;

import com.roadjava.demo09.bean.UserInfo9;
import com.roadjava.demo09.util.ValidationUtil9;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.groups.Default;
import java.util.List;

@RestController
public class UserInfoHandler9 {

    @GetMapping("/getByName")
    public String getByName(String name) {
        return name + "ok";
    }

    @GetMapping("/addUser4")
    public String addUser4(@Validated({UserInfo9.UpdateGroup.class, Default.class}) UserInfo9 userInfo, BindingResult bindingResult) {
        // 判读是否有不满足的约束
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                System.out.println(error.getObjectName() + ":" + error.getDefaultMessage());
            }

            // 获取没通过校验的字段详情
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage()
                        + "，当前没通过校验的值是：" + fieldError.getRejectedValue());
            }

            return "校验不成功";
        }
        return "添加成功";
    }

    @GetMapping("/addUser3")
    public String addUser3(@Valid UserInfo9 userInfo, BindingResult bindingResult) {
        // 判读是否有不满足的约束
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                System.out.println(error.getObjectName() + ":" + error.getDefaultMessage());
            }

            // 获取没通过校验的字段详情
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage()
                        + "，当前没通过校验的值是：" + fieldError.getRejectedValue());
            }

            return "校验不成功";
        }
        return "添加成功";
    }

    // springmvc环境中推荐声明式校验
    @GetMapping("/addUser2")
    public String addUser2(@Valid UserInfo9 userInfo) {
        return "添加成功";
    }

    // 编程式校验
    @GetMapping("/addUser1")
    public String addUser1(UserInfo9 userInfo) {
        List<String> result = ValidationUtil9.valid(userInfo);
        if (result.size() > 0) {
            System.out.println(result);
            return "校验不成功";
        } else {
            return "添加成功";
        }
    }
}